import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './user.entity';
import { Repository } from 'typeorm';
import { getUserDto } from './dto/get-user.dto';
import { conditionUtils } from 'src/utils/db.helper';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  // 查询所有用户
  async findAll(query: getUserDto): Promise<any> {
    const { page = 1, limit, username } = query;
    const take = limit || 10; // 指定每页的数据条目限制
    const skip = (page - 1) * take; // 计算需要跳过的数据条目数量
    const queryBuilder = this.userRepository
      .createQueryBuilder('user')
      .skip(skip)
      .take(limit);
    // 根据用户名查询用户信息
    const obj = {
      'user.username': username ? `%${username}%` : '',
    };
    const newQuery = conditionUtils<User>(queryBuilder, obj);
    const [data, total] = await Promise.all([
      newQuery.getMany(),
      newQuery.getCount(),
    ]);
    return { code: 200, msg: '请求成功！', data, total };
  }

  async createUser(user: Partial<User>): Promise<any> {
    // 检查是否存在相同的用户名
    // 创建新用户
    const newUser = this.userRepository.create(user);
    try {
      const createdUser = await this.userRepository.save(newUser);
      return { code: 200, msg: '用户创建成功！', data: createdUser };
    } catch (error) {
      throw new HttpException(error.sqlMessage, 500);
    }
  }
  async remove(id: number) {
    const user = await this.findOne(id);
    return this.userRepository.remove(user);
  }

  async update(id: number, user: Partial<User>) {
    const userTemp = await this.findProfile(id);
    const newUser = this.userRepository.merge(userTemp, user);
    // 联合模型
    return this.userRepository.save(newUser);
    // 下面的update只适合单个
    // return this.userRepository.update(id, user);
  }

  async findOne(id: number) {
    return this.userRepository.findOne({
      where: {
        id,
      },
    });
  }
  async find(username: string): Promise<any> {
    return this.userRepository.findOne({
      where: {
        username,
      },
    });
  }
  findProfile(id: number) {
    return this.userRepository.findOne({
      where: {
        id,
      },
    });
  }
}
